package com.shenzhen.horselive.ui.activity;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Pair;
import android.view.View;
import android.widget.ImageView;

import com.flqy.baselibrary.utils.GlideHelper;
import com.flqy.baselibrary.utils.T;

import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.shenzhen.horselive.R;
import com.shenzhen.horselive.User;
import com.shenzhen.horselive.api.ApiFactory;
import com.shenzhen.horselive.api.response.ApiResponse;
import com.shenzhen.horselive.base.AppBarActivity;
import com.shenzhen.horselive.beans.CommResponseBean;
import com.shenzhen.horselive.common.SafeConsumer;
import com.shenzhen.horselive.common.utils.Permissions;
import com.shenzhen.horselive.common.utils.handler.IFilterHandler;
import com.shenzhen.horselive.databinding.ActivityRealNameAuthBinding;
import com.shenzhen.horselive.network.SchedulersCompat;
import com.shenzhen.horselive.presenter.LoadingViewObserver;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;

import java.io.File;
import java.util.List;

import gun0912.tedbottompicker.PhotoPicker;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class RealNameAuthActivity extends AppBarActivity {

    private static final int REQUEST_CODE_CHOOSE =9001 ;
    private static final int REQUEST_CODE_CHOOSE1 =9002 ;
    ActivityRealNameAuthBinding  binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityRealNameAuthBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        setStyleDark();
        setTitle("实名认证");
        initViews();
    }

    String  path1,path2;
    private void initViews() {
       binding.imgCardZheng.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               XXPermissions.with(RealNameAuthActivity.this)
               .permission(Permission.Group.STORAGE)
                       .request(new OnPermission() {
                           @Override
                           public void hasPermission(List<String> granted, boolean all) {
                               if (all)
                               {

                                   Matisse.from(RealNameAuthActivity.this)
                                           .choose(MimeType.ofImage())
                                           .countable(false)
                                           .maxSelectable(1)
                                           .showSingleMediaType(true)
//                                    .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
//                                    .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
//                                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
//                                    .thumbnailScale(0.85f)
                                           .imageEngine(new GlideEngine())
//                                           .showPreview(false) // Default is `true`
                                           .forResult(REQUEST_CODE_CHOOSE);
                                   //有权限
                                   //权限申请成功
//                                   new PhotoPicker.Builder(RealNameAuthActivity.this).setSelectMaxCount(1)
//                                           .setOnImageSelectedListener(new PhotoPicker.OnImageSelectedListener() {
//                                               @Override
//                                               public void onImageSelected(Pair<Uri, String> imagePath) {
//                                                   path1 =  imagePath.second;
//                                                   GlideHelper.loadImage(path1,binding.imgCardZheng);
//
//
//                                               }
//                                           }).create().show();
                               }
                           }
                           @Override
                           public void noPermission(List<String> denied, boolean quick) {

                           }
                       });



           }
       });
       
       binding.imgCardFan.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               Permissions.of(RealNameAuthActivity.this).request(getString(R.string.take_photo_get_sdcard_error),
                       Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE).subscribe(new SafeConsumer<Boolean>() {
                   @Override
                   public void accept(Boolean granted) {
                       if (granted) {
                           //权限申请成功
                           Matisse.from(RealNameAuthActivity.this)
                                   .choose(MimeType.ofImage())
                                   .countable(false)
                                   .maxSelectable(1)
                                   .showSingleMediaType(true)
//                                    .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
//                                    .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
//                                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
//                                    .thumbnailScale(0.85f)
                                   .imageEngine(new GlideEngine())
                                   .showPreview(false) // Default is `true`
                                   .forResult(REQUEST_CODE_CHOOSE1);
                       } else {
                           //权限申请失败
                           T.showShort("权限申请失败");
                       }
                   }
               });

           }
       });
        

       binding.btGo.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               submit();
           }
       });



    }

    private void submit() {
        if (TextUtils.isEmpty(path1) || TextUtils.isEmpty(path2))
        {
            return;
        }
        //上传证件
        File  file1 = new File(path1);
        File  file2 = new File(path2);

        RequestBody fileBody1 = RequestBody.create(MediaType.parse("multipart/form-data"), file1);
        RequestBody fileBody2 = RequestBody.create(MediaType.parse("multipart/form-data"), file2);

        MultipartBody multipartBody = new MultipartBody.Builder()
                .addFormDataPart("frontImage", file1.getName(), fileBody1)
                .addFormDataPart("backImage", file2.getName(), fileBody2)
                .addFormDataPart("token", User.get().getMyInfo().getToken())
                .setType(MultipartBody.FORM)
                .build();
        ApiFactory.getApiService().realName(multipartBody)
                .compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new LoadingViewObserver<CommResponseBean>(this) {
                    @Override
                    protected void onNextInActive(CommResponseBean commResponseBean) {
                        if (commResponseBean.isSuccess())
                        {
                            showToast("已实名");
                            setResult(1001);
                            finish();
                        }
                        else
                        {
                            showToast(commResponseBean.getErrMessage());

                        }
                    }
                });

    }

    List<String> mSelected;
    List<String> mSelected1;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
//            mSelected = Matisse.obtainResult(data);
            mSelected =   Matisse.obtainPathResult(data);
            if (mSelected!=null&&mSelected.size()>0)
            {
                path1 = mSelected.get(0);
               GlideHelper.loadImage(path1,binding.imgCardZheng);
            }
        }
        if (requestCode == REQUEST_CODE_CHOOSE1 && resultCode == RESULT_OK) {
//            mSelected = Matisse.obtainResult(data);
            mSelected1 =   Matisse.obtainPathResult(data);
            if (mSelected1!=null&&mSelected1.size()>0)
            {
                path2 = mSelected1.get(0);
                GlideHelper.loadImage(path2,binding.imgCardFan);
            }
        }
    }
}